package com.muy.redis.view.window.redis;

import com.intellij.openapi.project.Project;
import com.muy.redis.common.tree.AbstractMTTreePanel;
import com.muy.redis.utils.JTreeUtils;
import com.muy.redis.utils.PasswordUtils;
import com.muy.redis.view.window.redis.bean.MrRedisConnectionParam;
import com.muy.redis.view.window.redis.configuration.MrRedisConfiguration;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisRoot;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisTopDb;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2023/9/15 20:16
 */
public class MrRedisTree extends AbstractMTTreePanel {


    public MrRedisTree(Project project) {
        super(project, false, new MTTreeCellMrRedisRoot(project));
        MrRedisConfiguration mrRedisConfiguration = MrRedisConfiguration.getInstance(project);
        List<MrRedisConnectionParam> entrances = mrRedisConfiguration.getEntrances();
        if (CollectionUtils.isNotEmpty(entrances)) {
            buildTree(entrances);
        }
    }

    @Override
    protected void installActions() {

    }

    /**
     * @param entrances
     */
    public void buildTree(List<MrRedisConnectionParam> entrances) {
        if (CollectionUtils.isEmpty(entrances)) {
            return;
        }

        for (MrRedisConnectionParam mrRedisConnectionParam : entrances) {
            if (StringUtils.isBlank(mrRedisConnectionParam.getId()) || mrRedisConnectionParam.getId().equals(mrRedisConnectionParam.getName())) {
                mrRedisConnectionParam.setId(mrRedisConnectionParam.genId());
            }

            if (StringUtils.isNotBlank(mrRedisConnectionParam.getId())) {
                String passwordRe = PasswordUtils.retrievePassword(mrRedisConnectionParam.getId());
                if (!StringUtils.isBlank(passwordRe)) {
                    mrRedisConnectionParam.setPassword(passwordRe);
                }
            }
            MTTreeCellMrRedisTopDb topDb = new MTTreeCellMrRedisTopDb(project, mrRedisConnectionParam);
            DefaultMutableTreeNode topDbTreeNode = new DefaultMutableTreeNode(topDb);
            rootTreeNode.add(topDbTreeNode);
        }
        JTreeUtils.reload(jTree(), rootTreeNode);
    }
}
